package com.zxgj.datadirect.controller;

import com.zxgj.datadirect.util.TestDataGenerator;
import com.zxgj.datadirect.domain.DataDirectExchangeTask;
import com.zxgj.datadirect.service.DataDirectExchangeTaskService;
import com.zxgj.datadirect.service.DataDirectExchangeTaskLogService;
import com.zxgj.datadirect.entity.DataDirectExchangeTaskLog;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 开发联调用：生成数据直达模块的测试数据。
 */
@Slf4j
@RestController
@RequestMapping("/datadirect/mock")
@RequiredArgsConstructor
public class MockDataController {

    private final TestDataGenerator testDataGenerator;
    private final DataDirectExchangeTaskService exchangeTaskService;
    private final DataDirectExchangeTaskLogService taskLogService;

    /**
     * 生成目录类测试数据（若已存在相同编码则跳过）。
     */
    @PostMapping("/catalog")
    public Map<String, Object> generateCatalogMock() {
        testDataGenerator.generateTestData();
        Map<String, Object> resp = new HashMap<>();
        resp.put("code", 200);
        resp.put("msg", "mock catalog data generated");
        return resp;
    }

    /**
     * 生成交换任务与日志的模拟数据
     */
    @PostMapping("/exchangeTask")
    public Map<String, Object> generateExchangeTaskMock() {
        for (int i = 1; i <= 8; i++) {
            DataDirectExchangeTask t = new DataDirectExchangeTask();
            t.setTaskName("联调任务-" + i);
            t.setTaskStatus(i % 3); // 0 待启动 1 运行中 2 已停止（示例）
            
            try { 
                // 先保存任务并获取ID
                DataDirectExchangeTask savedTask = exchangeTaskService.createTask(t).getData();
                Long taskId = savedTask.getId(); // 获取新创建的任务ID
                
                // 生成简单日志
                for (int j = 1; j <= 5; j++) {
                    try {
                        DataDirectExchangeTaskLog taskLog = new DataDirectExchangeTaskLog();
                        taskLog.setTaskId(taskId); // 使用正确的taskId
                        taskLog.setContent("任务" + t.getTaskName() + " 第" + j + "次交换完成");
                        taskLog.setLevel("INFO");
                        taskLogService.save(taskLog);
                    } catch (Exception e) {
                        log.error("生成任务日志失败: {}", e.getMessage());
                    }
                }
            } catch (Exception e) {
                log.error("生成交换任务失败: {}", e.getMessage());
            }
        }
        
        Map<String, Object> resp = new HashMap<>();
        resp.put("code", 200);
        resp.put("msg", "mock exchange task generated");
        return resp;
    }
}
